//
//  HDBeaconManager.m
//  HDSmartPenSDKDemo
//
//  Created by 牛的mini on 2016/12/26.
//  Copyright © 2016年 牛的mini. All rights reserved.
//

#import "HDBeaconManager.h"
#import "HDBeaconManager+Ext.h"
typedef enum {
    kSMPen_Command_Type_Unknown,
    kSMPen_Command_Type_A2,  // NFC
    kSMPen_Command_Type_A4   // Power
}
SMPenCommandType;

@interface HDBeaconManager()<BLEMangerDelegate,cbDiscoveryManagerDelegate,CBPeripheralDelegate>
{
    NSTimer    *scanTimer;
    BLEmanager *m_bleManger;
    BOOL       isPairing; //是否配对成功
    
    NSMutableArray *allInfoArray;
    NSMutableArray *publicArray;
    SMPenCommandType commandType;
    NSString *mySMPenID;
    
    NSInteger _pointCount; //离线点的数量
    NSString *_pointInfo; //点的信息
    BOOL _hasInfo; //是否有离线数据
    BOOL _endRead; //是否读取离线数据完毕
    BOOL _startRead;
}
@property (strong, nonatomic) CBCharacteristic *writeCharacteristic;
@property (strong, nonatomic) CBCharacteristic *readCharacteristic;
@end


@implementation HDBeaconManager

#pragma mark
#pragma mark -------- Init Methods --------

+ (id)sharedBeacon
{
    static id sharedBeacon;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedBeacon = [[self alloc] init];
        [sharedBeacon beaconInit];
    });
    
    return sharedBeacon;
}

- (void)beaconInit
{
    m_bleManger = [BLEmanager shareInstance];
    m_bleManger.mange_delegate = self;
    [[BLEmanager shareInstance] setCbDiscoveryDelegate:self];
    
    isPairing = NO;
    commandType = kSMPen_Command_Type_Unknown;
    mySMPenID = @"000000";
    
}

- (void)startBeacon
{
    if (!m_bleManger.cbCentralPoweredOn) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_State_Unopen_Notification object:nil];
        return;
    }
    
    NSLog(@"currentPeripheral:%@",[Common1 sharedInstance].currentPeripheral);
    [self scanPeripheralResult];

    if ([Common1 sharedInstance].currentPeripheral != nil)
    {
        if ([Common1 sharedInstance].currentPeripheral.state == CBPeripheralStateConnected)
        {
            //取消连接
            [m_bleManger.m_manger cancelPeripheralConnection:[Common1 sharedInstance].currentPeripheral];
        }
    }
    [m_bleManger startScanning];
}

- (void)stopScanAction
{
    [m_bleManger.m_manger stopScan];
}

-(void)scanPeripheralResult
{
    /*
     *采用定时器的方法，每隔3s，查询一下当前扫描到的所有外设
     */
    scanTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scanresult) userInfo:nil repeats:YES];
}

- (void)scanresult
{
    NSArray *tempArray = m_bleManger.m_array_peripheral;
    [[NSNotificationCenter defaultCenter] postNotificationName:kScan_Beacon_And_Reload_Notification object:tempArray];
}

- (NSString *)SMPenID
{ return mySMPenID; }

#pragma mark

- (void)connectPeripheral:(PeripheralModel *)peripheral
{
    if (peripheral != nil)
    {
        [m_bleManger.m_manger connectPeripheral:peripheral.discoveredPeripheral options:nil];
        [[Common1 sharedInstance] setCurrentPeripheral:peripheral.discoveredPeripheral];
    }
}

- (void)disconnectPeripheral:(PeripheralModel *)peripheral
{
    if (peripheral != nil)
    {
        [m_bleManger.m_manger cancelPeripheralConnection:peripheral.discoveredPeripheral];
        [[Common1 sharedInstance] setCurrentPeripheral:nil];
    }
}


- (void)searchSMPen
{
    NSData *value = [self hexToBytes:@"A0"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)heartBeatAction
{
    NSData *value = [self stringToByte:@"AF"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)searchSMPenIDAction // 返回智慧笔的ID
{
    NSData *value = [self hexToBytes:@"A1"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)writeLanguageAction:(NSInteger)selectIndex
{
    /*
     0xD1    中文
     0xD2    英文
     0xD3    法语
     0xD4    德语
     0xD5    意大利语
     0xD6    日语
     0xD7    韩语
     0xD8    葡萄牙语
     0xD9    俄语
     0xDA    泰文
     0xDB    印度文
     0xDC    西班牙语
     0xDD    希腊语
     0xDE    土耳其文
     0xDF    丹麦语

     */
    NSArray *languageArray = @[@"D1",@"D2",@"D6",@"D7",@"D3"];
    if (selectIndex < languageArray.count)
    {
        NSString *nowStr = languageArray[selectIndex];
        NSData *value = [self stringToByte:nowStr];
        [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
    else
    {
        [LCCoolHUD showFailure:@"参数错误" zoom:NO shadow:NO];
    }
}

- (void)writeLEDAction:(NSInteger)selectIndex
{
    /*
     0xC1    红
     0xC2    绿
     0xC3    蓝
     0xC4    青
     0xC5    粉
     0xC6    黄
     0xC7    白
     */
    NSArray *LEDArray = @[@"C1",@"C2",@"C3",@"C4",@"C5",@"C6",@"C7"];
    if (selectIndex < LEDArray.count)
    {
        NSString *nowStr = LEDArray[selectIndex];
        NSData *value = [self stringToByte:nowStr];
        [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_LED_Parameter_Error_Notification object:nil];
    }
}

- (void)playMp3Action:(NSString *)playNo
{
    NSString *hexNo = [self smPenToHex:playNo.integerValue];
    
    NSString *hexA = [hexNo substringToIndex:2];
    NSString *hexB = [hexNo substringFromIndex:2];
    NSString *hexC = [self pinxCreator:hexA withPinv:hexB];
    NSString *hexD = [self pinxCreator:hexC withPinv:@"BC"];
    
    NSData *dataA  = [self stringToByte:@"BC"];
    NSData *dataB  = [self stringToByte:hexA];
    NSData *dataC  = [self stringToByte:hexB];
    NSData *dataD  = [self stringToByte:hexD];
    
    [[Common1 sharedInstance].currentPeripheral writeValue:dataA forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [[Common1 sharedInstance].currentPeripheral writeValue:dataB forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [[Common1 sharedInstance].currentPeripheral writeValue:dataC forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [[Common1 sharedInstance].currentPeripheral writeValue:dataD forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)syncData{
    _pointInfo = nil;
    _pointCount = 0;
    _hasInfo = NO;
    _endRead = NO;
    NSData *value = [self hexToBytes:@"A5"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

// 读取全部的信息
- (void)readAllInfoAction
{
    NSData *value = [self stringToByte:@"BA"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)nfcChanged:(BOOL)isON
{
    NSData *value = [self hexToBytes:@"A3"];
    if (isON == YES)
    {value = [self hexToBytes:@"A2"];}
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)volumeIndexChange:(NSInteger)volumeIndex
{
    NSArray *volumeArray = @[@"E0",@"E1",@"E2",@"E3",@"E4",@"E5",@"E6",@"E7",@"E8",@"E9",@"EA",@"EB",@"EC",@"ED",@"EE",@"EF"];
    if (volumeIndex < volumeArray.count)
    {
        NSString *eStr = volumeArray[volumeIndex];
        NSData *value = [self hexToBytes:eStr];
        [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
    else
    {
        NSLog(@"下标错误！");
    }
}

- (void)readPowerAction
{
    NSData *value = [self stringToByte:@"A4"];
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)pairConnectAction
{
    NSData *value = [self stringToByte:@"AF"];
    isPairing = YES;
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

#pragma mark -------- mark_BLEMangerDelegate --------

-(void)bleMangerConnectedPeripheral :(BOOL)isConnect;
{
    if (isConnect == YES) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_Connect_Successful_Notification object:nil];
        _isConnected = YES;
        
        [[Common1 sharedInstance].currentPeripheral setDelegate:self];
        [[Common1 sharedInstance].currentPeripheral discoverServices:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self searchSMPenIDAction];
        });
        
        [m_bleManger.m_manger stopScan];
    }
}


#pragma mark
#pragma mark -------CBPeripheralDelegate---------

-(void)bleMangerDisConnectedPeripheral:(CBPeripheral *)_peripheral;
{
    if ([_peripheral isEqual:[Common1 sharedInstance].currentPeripheral]) {
        NSLog(@ "已经断开了链接");
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_Disconnect_Successful_Notification object:nil];
        _isConnected = NO;
        [self scanPeripheralResult]; //调用扫描
    }
}

//3.搜索服务的Delegate 若发现服务，然后搜索其内的特征服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        //      NSLog(@"didDiscoverServices : %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *s in peripheral.services)
    {
        //查找特征字节
        [s.peripheral discoverCharacteristics:nil forService:s];
    }
}

//4.搜索特征的Delegate 若发现特征，则看看这个“通道是发送的还是接收”，接收就read，发送就把这个writeCharacteristic记录下

/*z
 
 //注意：不是所有的特性值都是可读的（readable）。通过访问 CBCharacteristicPropertyRead 可以知道特性值是否可读。如果一个特性的值不可读，使用 peripheral:didUpdateValueForCharacteristic:error:就会返回一个错误。
 //Subscribing to a Characteristic’s Value(订制一个特性值) 尽管通过 readValueForCharacteristic:方法能够得到特性值，但是对于一个变化的特性值就不是很 有效了。大多数的特性值是变化的，比如一个心率监测应用，如果需要得到特性值，就需要 通过预定的方法获得。当预定了一个特性值，当值改变时，就会收到设备发出的通知。
 
 特征值的属性：c.properties
 typedef NS_OPTIONS(NSInteger, CBCharacteristicProperties) {
 // 标识这个characteristic的属性是广播
 CBCharacteristicPropertyBroadcast= 0x01,
 // 标识这个characteristic的属性是读
 CBCharacteristicPropertyRead= 0x02,
 // 标识这个characteristic的属性是写-没有响应
 CBCharacteristicPropertyWriteWithoutResponse= 0x04,
 // 标识这个characteristic的属性是写
 CBCharacteristicPropertyWrite= 0x08,
 // 标识这个characteristic的属性是通知
 CBCharacteristicPropertyNotify= 0x10,
 // 标识这个characteristic的属性是声明
 CBCharacteristicPropertyIndicate= 0x20,
 // 标识这个characteristic的属性是通过验证的
 CBCharacteristicPropertyAuthenticatedSignedWrites= 0x40,
 // 标识这个characteristic的属性是拓展
 CBCharacteristicPropertyExtendedProperties= 0x80,
 // 标识这个characteristic的属性是需要加密的通知
 CBCharacteristicPropertyNotifyEncryptionRequiredNS_ENUM_AVAILABLE(NA, 6_0)= 0x100,
 // 标识这个characteristic的属性是需要加密的申明
 CBCharacteristicPropertyIndicateEncryptionRequiredNS_ENUM_AVAILABLE(NA, 6_0)= 0x200
 };
 
 */

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if (error)
    {
        NSLog(@"didDiscoverCharacteristicsForService error : %@", [error localizedDescription]);
        return;
    }
    
    for (CBCharacteristic *c in service.characteristics)
    {
        NSLog(@"\n>>>\t特征UUID FOUND(in 服务UUID:%@): %@ (data:%@)",service.UUID.description,c.UUID,c.UUID.data);
        
        //假如你和硬件商量好了，某个UUID时写，某个读的，那就不用判断啦
        if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]])
        {   //Read Write
            [Common1 sharedInstance].writeCharacteristic = c;
            _writeCharacteristic = c;
        }
        if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]){
            //Read
            [Common1 sharedInstance].readCharacteristic = c;
            [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:c];
            _readCharacteristic = c;
        }
        if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF3"]]){
            //Write
            
        }
        if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]){
            //Notify
            [[Common1 sharedInstance].currentPeripheral setNotifyValue:YES forCharacteristic:c];
            
        }
        if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF5"]]){
            //Read
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"数据发生改变:%@", characteristic);
    NSData *cData = characteristic.value;
    NSString *allInfo = [self hexadecimalString:cData];
    NSData *valueA1 = [self stringToByte:@"A1"];
    NSData *valueA2 = [self stringToByte:@"A2"];
    NSData *valueAF = [self stringToByte:@"AF"];
    NSData *valueBA = [self stringToByte:@"BA"];
    NSData *valueA5 = [self stringToByte:@"A5"];
    
    if ([allInfo hasPrefix:@"ba"] && allInfo.length > 2)
    {
        [self  handleAllInfo:allInfo];
    }
    else if ([allInfo hasPrefix:@"a1"] && allInfo.length > 2)
    {
        [self handleSMPenID:allInfo];
    }
    else if ([allInfo hasPrefix:@"e"]) // 电量
    {
        NSString *volumeStr = [self volumeIndexStr:allInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_Volume_Successful_Notification
                                                            object:volumeStr];
    }
    else if ([allInfo hasPrefix:@"a2"] && allInfo.length>2){
        [self handleNFCWithAllInfo:allInfo];
    }
    else if ([allInfo hasPrefix:@"aa55"] || (_pointInfo.length-8)/10 < _pointCount || _startRead){
        [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
        [self commandActionWithChargeValue:allInfo];
    }
    
    
    if ([cData isEqualToData:valueAF]) {
        
        [self handlePair:allInfo];
    }
    else if ([cData isEqualToData:valueBA]) {
        [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];

    }
    else if ([characteristic.value isEqualToData:valueA1]) {
        NSLog(@"SMPen的ID是 :%@", [Common1 sharedInstance].readCharacteristic);
        [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
    }
    else if ([cData isEqualToData:valueA2]){
        [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
        return;
    }
    else if([cData isEqualToData:valueA5]){
        _startRead = YES;
        [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
        
        return;
    }
    else //电量
    {
        //16转2进制
        NSString *binary = [self getBinaryByhex:allInfo binary:nil];
        //    2转10进制
        NSString *m = [self toDecimalWithBinary:binary];
        if ([allInfo isEqualToString:@"ff"])
        {
            commandType = kSMPen_Command_Type_A4;
            publicArray = [NSMutableArray arrayWithCapacity:4];
        }

        if (commandType == kSMPen_Command_Type_A4 )
        {
            if (publicArray.count < 3) {
                [publicArray addObject:m];
                NSLog(@"publicArray:%@",publicArray);
            }else
            {
                NSString *power = publicArray[1];
                [LCCoolHUD showSuccess:power zoom:YES shadow:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_Power_Notification object:power];
                [publicArray removeAllObjects];
                publicArray = nil;
            }
        }
     
    }
    
}

#pragma mark ---DataAnalysis----
//智慧笔ID
- (void)handleSMPenID:(NSString *)smPenID{
    NSLog(@"SMPen ID is %@", smPenID);
    mySMPenID = smPenID;
    
}

//智慧笔的所有模块信息
- (void)handleAllInfo:(NSString *)allInfo{
    NSLog(@"all info is %@", allInfo);
    NSInteger strLen = allInfo.length;
    if ( strLen%2 == 0)
    {
        NSMutableArray *infoArray = [NSMutableArray arrayWithCapacity:20];
        NSInteger startIndex = 0;
        while (startIndex<= strLen-2) {
            NSRange range = NSMakeRange(startIndex, 2);
            NSString *subStr = [allInfo substringWithRange:range];
            [infoArray addObject:subStr];
            startIndex += 2;
        }
        [self infoChangeAction:infoArray];
        NSArray *sendArray = @[infoArray[3],infoArray[6],infoArray[5],infoArray[4],infoArray[7]];
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_Part_Info_Notification object:sendArray];
        
        NSArray *smpenInfoArray = @[mySMPenID,infoArray[8],infoArray[10],infoArray[12],infoArray[11],infoArray[4],infoArray[5],infoArray[6],infoArray[3],infoArray[7]];
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_All_Info_Notification object:smpenInfoArray];
    }

}

//配对、心跳包
- (void)handlePair:(NSString *)allInfo{
    if ( isPairing == YES)
    {
        //NSLog(@"***************配对成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_Pair_Successful_Notification object:nil];
        _isConnected = YES;
        isPairing = NO;
        
        //[self readAllInfoAction];
    }
    else
    {
        //NSLog(@"***************心跳成功");
        _isConnected = YES;
    }
}

- (void)handleNFCWithAllInfo:(NSString *)chargeValue{
    //截取掉前两位的标志位 a2 0001 00 03 14
    chargeValue = [chargeValue substringFromIndex:2];
    if (chargeValue.length >= 10) {
        NSMutableArray *myPoints = [NSMutableArray arrayWithCapacity:0];
        //点的编号
        NSString *numString = [self binaryToDecimalWithBinary:[chargeValue substringToIndex:4]];
        //日
        NSString *day = [self binaryToDecimalWithBinary:[chargeValue substringWithRange:NSMakeRange(4, 2)]];
        //时
        NSString *hour = [self binaryToDecimalWithBinary:[chargeValue substringWithRange:NSMakeRange(6, 2)]];
        //分
        NSString *mint = [self binaryToDecimalWithBinary:[chargeValue substringWithRange:NSMakeRange(8, 2)]];
        NSDictionary *infoDic = @{
                                  @"e_id":numString,
                                  @"d":day,
                                  @"h":hour,
                                  @"i":mint,
                                  @"l_t":@0
                                  };
        [myPoints addObject:infoDic];
        [[NSNotificationCenter defaultCenter]postNotificationName:kBeacon_SMPen_NFC_Info_Notification object:myPoints];
    }
    
}


- (void)commandActionWithChargeValue:(NSString *)chargeValue{
    
    //aa550005 0001121212 001121212 001121212
    /**同步数据**/
    if ([chargeValue hasPrefix:@"aa55"]){
        _hasInfo  = YES;
        //点的数量以aa55开始
        //aa550004 表示点的数量去04
        NSString *pointCountStr = [chargeValue substringToIndex:8];
        if (pointCountStr.length>=8) {
            pointCountStr = [pointCountStr substringFromIndex:4];
            //16转2进制
            NSString *binary = [self getBinaryByhex:pointCountStr binary:nil];
            //2转10进制
            NSString *m = [self toDecimalWithBinary:binary];
            _pointCount = m.integerValue;  //点的数量
        }
        
    }else{
        if (!_hasInfo) {
            [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
        }
    }
    
    if (_pointCount != 0) {
        if (_pointInfo == nil) {
            _pointInfo = chargeValue;
        }else{
            
            _pointInfo = [NSString stringWithFormat:@"%@%@",_pointInfo,chargeValue];
        }
        if ((_pointInfo.length-8)/10 >= _pointCount) {
            [self getPointInfoWith:_pointInfo];
        }else{
            [[Common1 sharedInstance].currentPeripheral readValueForCharacteristic:[Common1 sharedInstance].readCharacteristic];
        }
    }else{
        
    }
}

- (void)getPointInfoWith:(NSString *)info{
    info = [info substringFromIndex:8];
    NSInteger currentIndex = 0;
    NSMutableArray *myPoints = [NSMutableArray arrayWithCapacity:0];
    while (currentIndex < _pointCount) {
        NSString *point = [info substringWithRange:NSMakeRange(currentIndex*10, 10)];
        if (point.length >= 10) {
            //点的编号
            NSString *numString = [self binaryToDecimalWithBinary:[point substringToIndex:4]];
            //日
            NSString *day = [self binaryToDecimalWithBinary:[point substringWithRange:NSMakeRange(4, 2)]];
            //时
            NSString *hour = [self binaryToDecimalWithBinary:[point substringWithRange:NSMakeRange(6, 2)]];
            //分
            NSString *mint = [self binaryToDecimalWithBinary:[point substringWithRange:NSMakeRange(8, 2)]];
            NSDictionary *infoDic = @{
                                      @"e_id":numString,
                                      @"d":day,
                                      @"h":hour,
                                      @"i":mint,
                                      @"l_t":@0
                                      };
            [myPoints addObject:infoDic];
            currentIndex += 1;
        }
    }
    
    if (myPoints.count > 0) {
        _pointCount = 0;
        _pointInfo = nil;
        [[NSNotificationCenter defaultCenter]postNotificationName:kBeacon_SMPen_Data_Notification object:myPoints];
        _startRead = NO;
    }
}

/**************滁州博物馆（同步数据、读取NFC标签），请看以上代码*****************************/
//十六进制转十进制
- (NSString *)binaryToDecimalWithBinary:(NSString *)chargeValue{
    //16转2进制
    NSString *binary = [self getBinaryByhex:chargeValue binary:nil];
    //    2转10进制
    NSString *m = [self toDecimalWithBinary:binary];
    return m;
}


/*
#pragma mark ---------------------------
- (void)showCharge
{
    NSLog(@"----------%@",publicArray);
    NSString *info1 = [publicArray lastObject];
    //16转2进制
    NSString *binary = [self getBinaryByhex:info1 binary:nil];
    //    2转10进制
    NSString *power = [self toDecimalWithBinary:binary];

    NSLog(@"电量：%@", power);
    // 发个通知出去
    if (commandType == kSMPen_Command_Type_A2)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_NFC_Info_Notification object:power];
    }
    else if (commandType == kSMPen_Command_Type_A4)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_SMPen_Power_Notification object:power];
    }
    
    // 变量置空
    commandType = kSMPen_Command_Type_Unknown;
    [publicArray removeAllObjects];
    publicArray = nil;
}
 */

- (NSString *)volumeIndexStr:(NSString *)strTemp
{
    NSArray *volumeArray = @[@"E0",@"E1",@"E2",@"E3",@"E4",@"E5",@"E6",@"E7",@"E8",@"E9",@"EA",@"EB",@"EC",@"ED",@"EE",@"EF"];
    NSInteger nowIndex = [volumeArray indexOfObject:strTemp.uppercaseString];
    return [NSString stringWithFormat:@"%li", (long)nowIndex];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"Error changing notification state: %@", [error localizedDescription]);
    }
    NSLog(@"收到通知:%@", characteristic);
}

// 向peripheral中写入数据后的回调函数，用于读取智慧笔中的数据
- (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]){
        //Read
        NSLog(@"读出数据成功: %@", characteristic);
        NSLog(@"Error is : %@", error);
    }
}

#pragma  mark
#pragma mark ---------UITableViewDataSource ----------

- (void)infoChangeAction:(NSMutableArray *)infoArray
{
    if (infoArray.count > 1) //NFC开关
    {
        NSString *info1 = infoArray[1];
        if ([info1 isEqualToString:@"a2"])
        {infoArray[1] = @"1";}
        else if ([info1 isEqualToString:@"a3"])
        {infoArray[1] = @"0";}
    }
    if (infoArray.count > 2) //LED颜色
    {
        /*
         0xC8    红
         0xC9    绿
         0xCA    蓝
         0xCB    青
         0xCC    粉
         0xCD    黄
         0xCE    白
         */
        NSString *info1 = infoArray[2];
        if ([info1 isEqualToString:@"c8"])
        {infoArray[2] = @"红";}
        else if ([info1 isEqualToString:@"c9"])
        {infoArray[2] = @"绿";}
        else if ([info1 isEqualToString:@"ca"])
        {infoArray[2] = @"蓝";}
        else if ([info1 isEqualToString:@"cb"])
        {infoArray[2] = @"青";}
        else if ([info1 isEqualToString:@"cc"])
        {infoArray[2] = @"粉";}
        else if ([info1 isEqualToString:@"cd"])
        {infoArray[2] = @"黄";}
        else if ([info1 isEqualToString:@"ce"])
        {infoArray[2] = @"白";}
    }
    if (infoArray.count > 3) // mp3
    {
        NSString *info1 = infoArray[3];
        if ([info1 isEqualToString:@"b0"])
        {infoArray[3] = @"1";}
        else if ([info1 isEqualToString:@"b1"])
        {infoArray[3] = @"0";}
    }
    if (infoArray.count > 4) // BLE
    {
        NSString *info1 = infoArray[4];
        if ([info1 isEqualToString:@"b2"])
        {infoArray[4] = @"1";}
        else if ([info1 isEqualToString:@"b3"])
        {infoArray[4] = @"0";}
    }
    if (infoArray.count > 5) // 红外
    {
        NSString *info1 = infoArray[5];
        if ([info1 isEqualToString:@"b4"])
        {infoArray[5] = @"1";}
        else if ([info1 isEqualToString:@"b5"])
        {infoArray[5] = @"0";}
    }
    if (infoArray.count > 6) // RFID
    {
        NSString *info1 = infoArray[6];
        if ([info1 isEqualToString:@"b6"])
        {infoArray[6] = @"1";}
        else if ([info1 isEqualToString:@"b7"])
        {infoArray[6] = @"0";}
    }
    if (infoArray.count > 7) // 报警
    {
        NSString *info1 = infoArray[7];
        if ([info1 isEqualToString:@"b8"])
        {infoArray[7] = @"1";}
        else if ([info1 isEqualToString:@"b9"])
        {infoArray[7] = @"0";}
    }
    if (infoArray.count > 8) // 电量
    {
        NSString *info1 = infoArray[8];
        //16转2进制
        NSString *binary = [self getBinaryByhex:info1 binary:nil];
        //    2转10进制
        NSString *power = [self toDecimalWithBinary:binary];
        infoArray[8] = power;
    }
    if (infoArray.count > 9) //震动等级
    {
        NSString *info1 = infoArray[9];
        if ([info1 isEqualToString:@"a7"])
        {infoArray[9] = @"1";}
        else if ([info1 isEqualToString:@"a8"])
        {infoArray[9] = @"2";}
        else if ([info1 isEqualToString:@"a9"])
        {infoArray[9] = @"3";}
        else if ([info1 isEqualToString:@"aa"])
        {infoArray[9] = @"4";}
        else if ([info1 isEqualToString:@"ab"])
        {infoArray[9] = @"0";}
    }
    if (infoArray.count > 10) //待机LED颜色
    {
        /*
         0xC1    红
         0xC2    绿
         0xC3    蓝
         0xC4    青
         0xC5    粉
         0xC6    黄
         0xC7    白
         */
        NSString *info1 = infoArray[10];
        if ([info1 isEqualToString:@"c1"])
        {infoArray[10] = @"红";}
        else if ([info1 isEqualToString:@"c2"])
        {infoArray[10] = @"绿";}
        else if ([info1 isEqualToString:@"c3"])
        {infoArray[10] = @"蓝";}
        else if ([info1 isEqualToString:@"c4"])
        {infoArray[10] = @"青";}
        else if ([info1 isEqualToString:@"c5"])
        {infoArray[10] = @"粉";}
        else if ([info1 isEqualToString:@"c6"])
        {infoArray[10] = @"黄";}
        else if ([info1 isEqualToString:@"c7"])
        {infoArray[10] = @"白";}
    }
    if (infoArray.count > 11) //语种
    {
        /*
         0xD1    中文
         0xD2    英文
         0xD3    法语
         0xD4    德语
         0xD5    意大利语
         0xD6    日语
         0xD7    韩语
         0xD8    葡萄牙语
         0xD9    俄语
         0xDA    泰文
         0xDB    印度文
         0xDC    西班牙语
         0xDD    希腊语
         0xDE    土耳其文
         0xDF    丹麦语
         */
        NSString *info1 = infoArray[11];
        if ([info1 isEqualToString:@"d1"])
        {infoArray[11] = @"中文";}
        else if ([info1 isEqualToString:@"d2"])
        {infoArray[11] = @"英文";}
        if ([info1 isEqualToString:@"d3"])
        {infoArray[11] = @"法语";}
        else if ([info1 isEqualToString:@"d4"])
        {infoArray[11] = @"德语";}
        if ([info1 isEqualToString:@"d5"])
        {infoArray[11] = @"意大利语";}
        else if ([info1 isEqualToString:@"d6"])
        {infoArray[11] = @"日语";}
        if ([info1 isEqualToString:@"d7"])
        {infoArray[11] = @"韩语";}
        else if ([info1 isEqualToString:@"d8"])
        {infoArray[11] = @"葡萄牙语";}
        if ([info1 isEqualToString:@"d9"])
        {infoArray[11] = @"俄语";}
        else if ([info1 isEqualToString:@"da"])
        {infoArray[11] = @"泰文";}
        if ([info1 isEqualToString:@"db"])
        {infoArray[11] = @"印度文";}
        else if ([info1 isEqualToString:@"dc"])
        {infoArray[11] = @"西班牙语";}
        if ([info1 isEqualToString:@"dd"])
        {infoArray[11] = @"希腊语";}
        else if ([info1 isEqualToString:@"de"])
        {infoArray[11] = @"土耳其文";}
        else if ([info1 isEqualToString:@"df"])
        {infoArray[11] = @"丹麦语";}
    }
    if (infoArray.count > 12) //音量
    {
        NSString *info1 = infoArray[12];
        if ([info1 isEqualToString:@"e0"])
        {infoArray[12] = @"0";}
        else if ([info1 isEqualToString:@"e1"])
        {infoArray[12] = @"1";}
        else if ([info1 isEqualToString:@"e2"])
        {infoArray[12] = @"1";}
        if ([info1 isEqualToString:@"e3"])
        {infoArray[12] = @"2";}
        else if ([info1 isEqualToString:@"e4"])
        {infoArray[12] = @"3";}
        if ([info1 isEqualToString:@"e5"])
        {infoArray[12] = @"4";}
        else if ([info1 isEqualToString:@"e6"])
        {infoArray[12] = @"5";}
        if ([info1 isEqualToString:@"e7"])
        {infoArray[12] = @"6";}
        else if ([info1 isEqualToString:@"e8"])
        {infoArray[12] = @"7";}
        if ([info1 isEqualToString:@"e9"])
        {infoArray[12] = @"8";}
        else if ([info1 isEqualToString:@"ea"])
        {infoArray[12] = @"9";}
        if ([info1 isEqualToString:@"eb"])
        {infoArray[12] = @"10";}
        else if ([info1 isEqualToString:@"ec"])
        {infoArray[12] = @"11";}
        if ([info1 isEqualToString:@"ed"])
        {infoArray[12] = @"12";}
        else if ([info1 isEqualToString:@"ee"])
        {infoArray[12] = @"13";}
        else if ([info1 isEqualToString:@"ef"])
        {infoArray[12] = @"14";}
    }
}

-(void)connectPeripheralFailed
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kBeacon_Disconnect_Successful_Notification object:nil];
    _isConnected = NO;
    [self scanPeripheralResult]; //调用扫描
}

#pragma mark 
#pragma mark ----------cbDiscoveryManagerDelegate------------

-(void)discoveryDidRefresh
{ NSLog(@"发现新的蓝牙外设"); }


#pragma mark
#pragma mark -------NSDate--NSString----
//自定义的写入数据的函数
/*
- (void)writeToPeripheral:(NSString *)string{
    if(![Common1 sharedInstance].writeCharacteristic){
        NSLog(@"writeCharacteristic is nil!");
        return;
    }
    NSData* value  = [self transformToByte:string];
    //    NSData* value = [self stringToByte:string];
    NSLog(@"Witedata: %@",value);
    
    [[Common1 sharedInstance].currentPeripheral writeValue:value forCharacteristic:[Common1 sharedInstance].writeCharacteristic type:CBCharacteristicWriteWithResponse];
}
- (NSData *)transformToByte:(NSString *)str
{
    // 将16进制数据转化成Byte 数组
    NSString *hexString = str; //16进制字符串
    int j=0;
    Byte bytes[128];  ///3ds key的Byte 数组， 128位
    for(int i=0;i<[hexString length];i++)
    {
        int int_ch;  /// 两位16进制数转化后的10进制数
        
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
        NSLog(@"int_ch=%d",int_ch);
        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
        j++;
    }
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:128];
    NSLog(@"newData=%@",newData);
    return newData;
}

*/
@end
